package testClient.customerClient;

import DTRSFrontEnd.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;

//client code
public class CustomerClient {

    FrontEnd fe;
    NamingContextExt ncRef;
    String city;

    public CustomerClient(String[] args, String show) {
        try {
            //create and initialize ORB
            ORB orb = ORB.init(args, null);
            //get root naming context
            org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
            ncRef = NamingContextExtHelper.narrow(objRef);
            city = lookUpFrontEndName(show);
            //set front end
            setFrontEnd(show);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //get FrontEnd based on showID
    private static String lookUpFrontEndName(String showID) {
	return showID.substring(0,3);
    }

    public void setFrontEnd(String show) {
        try {
            String name = lookUpFrontEndName(show);
            //get front end 
            fe = FrontEndHelper.narrow(ncRef.resolve_str(name));
            city = name;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    //get number of tickets available for show
    public int check(String showID) {
	if (!city.equals(lookUpFrontEndName(showID))) {
	    System.out.println("resetting front end");
            setFrontEnd(showID);
	}
	return fe.check(showID);
    }

    //reserve tickets for show under ID
    public boolean reserve(int ID, int tickets, String show) {
	if (!city.equals(lookUpFrontEndName(show))) {
	    System.out.println("resetting front end");
            setFrontEnd(show);
	}
        return fe.reserve(ID, tickets, show);
    }

    //cancel ID's tickets for show
    public boolean cancel(int ID, int tickets, String show) {
	if (!city.equals(lookUpFrontEndName(show))) {
	    System.out.println("resetting front end");
            setFrontEnd(show);
	}
        return fe.cancel(ID, tickets, show);
    }
    //exchange reservedTickets for desiredTickets if possible
    public boolean exchange(int customerID, String reservedShowID, int reservedTickets, String desiredShow, int desiredTickets){
	if (!city.equals(lookUpFrontEndName(reservedShowID))) {
	    System.out.println("resetting front end");
            setFrontEnd(reservedShowID);
	}
        return fe.exchange(customerID, reservedShowID, reservedTickets, desiredShow, desiredTickets);
    }

}
